package com.jrx.anytxn.accounting.service.impl;

import com.jrx.anytxn.accounting.bean.GlInterfaceInvestorBean;
import com.jrx.anytxn.accounting.constant.AccountBizConstant;
import com.jrx.anytxn.accounting.entity.GaVoucherInfo;
import com.jrx.anytxn.accounting.entity.TlGlInterfaceInvestorInfoExcp;
import com.jrx.anytxn.accounting.service.ITlGlInterfaceInvestorInfoService;
import com.jrx.anytxn.common.uitl.StringUtils;
import com.jrx.anytxn.investor.entity.TlGlInterfaceInvestorInfo;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.dto.aviator.RuleMatchReq;
import com.jrx.anytxn.param.entity.GaSubjectAccountConfig;
import com.jrx.anytxn.param.service.account.ISubjectAccountConfigService;
import com.jrx.anytxn.param.service.aviator.IAviatorService;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TlGlInterfaceInvestorInfoServiceImpl implements ITlGlInterfaceInvestorInfoService {

    private static final Logger logger = LoggerFactory.getLogger(TlGlInterfaceInvestorInfoServiceImpl.class);

    @Autowired
    private ISegmentService segmentService;
    @Autowired
    private IAviatorService aviatorService;
    @Autowired
    private ISubjectAccountConfigService subjectAccountConfigService;

    @Override
    public GlInterfaceInvestorBean getGlInterfaceInvestorBean(TlGlInterfaceInvestorInfo tlGlInterfaceInvestorInfo) throws Exception {
        GlInterfaceInvestorBean glInterfaceInvestorBean = new GlInterfaceInvestorBean();
        List<GaVoucherInfo> voucherInfoList = new ArrayList<>();
        List<TlGlInterfaceInvestorInfoExcp> tlGlInterfaceInvestorInfoExcpList = new ArrayList<>();
        //执行规则，获取规则结果
        Map map = new HashMap();
        //会计拆分规则条件
        map.put("organizationId", tlGlInterfaceInvestorInfo.getOrganizationId());
        map.put("txnCode", tlGlInterfaceInvestorInfo.getTxnCode());
        map.put("loanProductId", tlGlInterfaceInvestorInfo.getLoanProductId());
        map.put("loanClassify", tlGlInterfaceInvestorInfo.getLoanClassify());
        map.put("category", tlGlInterfaceInvestorInfo.getCategory());
        map.put("channel", tlGlInterfaceInvestorInfo.getChannel());
        map.put("totalTenor", tlGlInterfaceInvestorInfo.getTotalTenor());
        map.put("totalDays", tlGlInterfaceInvestorInfo.getTotalDays());
        map.put("accountStatus", tlGlInterfaceInvestorInfo.getAccountingPhase());
        map.put("liabilityFlag", tlGlInterfaceInvestorInfo.getLiabilityFlag());
        map.put("investorId", tlGlInterfaceInvestorInfo.getInvestorId());

        //执行会计核算规则
        RuleMatchReq ruleMatchReq = new RuleMatchReq(tlGlInterfaceInvestorInfo.getOrganizationId(), null,
                TransBizConstant.VOUCHER_RULE_SET, map, tlGlInterfaceInvestorInfo.getTenantId());
        //获取所有的会计核算结果信息
        List<Map<String, Object>> resultMapList = aviatorService.executeRuleList(ruleMatchReq);

        //没有匹配的规则，加入到总账流水例外表中
        if (CollectionUtils.isEmpty(resultMapList)) {
            TlGlInterfaceInvestorInfoExcp tlGlInterfaceInvestorInfoExcp = new TlGlInterfaceInvestorInfoExcp();
            BeanUtils.copyProperties(tlGlInterfaceInvestorInfo, tlGlInterfaceInvestorInfoExcp);
            tlGlInterfaceInvestorInfoExcpList.add(tlGlInterfaceInvestorInfoExcp);
            glInterfaceInvestorBean.setTlGlInterfaceInvestorInfoExcpList(tlGlInterfaceInvestorInfoExcpList);
            return glInterfaceInvestorBean;
        }

        int count = 0;
        for (Map<String, Object> resultMap : resultMapList) {
            List<GaVoucherInfo> gaVoucherInfoList = this.getByConditions(resultMap, tlGlInterfaceInvestorInfo, count);
            List<String> subjectIdList = (List<String>) resultMap.get(AccountBizConstant.RULE_RESULT_SUBJECT);
            count = count + subjectIdList.size();
            voucherInfoList.addAll(gaVoucherInfoList);
        }

        glInterfaceInvestorBean.setGaVoucherInfoList(voucherInfoList);

        return glInterfaceInvestorBean;
    }

    private List<GaVoucherInfo> getByConditions(Map<String, Object> resultMap, TlGlInterfaceInvestorInfo info, Integer count) throws Exception {
        List<GaVoucherInfo> voucherInfoList = new ArrayList<>();
        List<String> subjectIdList = (List<String>) resultMap.get(AccountBizConstant.RULE_RESULT_SUBJECT);
        int subjectCount = 0;
        for (String subjectId : subjectIdList) {
            subjectCount++;
            //创建传票流水
            GaVoucherInfo gaVoucherInfo = new GaVoucherInfo();
            gaVoucherInfo.setId(segmentService.getId(AccountBizConstant.TABLE_VOUCHERINFO));
            gaVoucherInfo.setTenantId(info.getTenantId());
            gaVoucherInfo.setOrganizationId(info.getOrganizationId());
            gaVoucherInfo.setBusinessDate(info.getGlDate());
            gaVoucherInfo.setFlowno(info.getGlFlowno());
            gaVoucherInfo.setSeq(count + subjectCount);

            //查询科目产品内部户映射配置
            GaSubjectAccountConfig subjectAccountConfig = subjectAccountConfigService.findBySubjectIdAndProductId(subjectId,info.getTenantId(),info.getLoanProductId());
            if(subjectAccountConfig!=null){
                //若科目+产品  有对应的内部户配置   则使用内部户账号生成传票
                subjectId = subjectAccountConfig.getInnerAccount();
            }

            gaVoucherInfo.setSubjectId(subjectId);
            gaVoucherInfo.setSign((String) resultMap.get(AccountBizConstant.RULE_RESULT_VOUCHERINFOSIGN));
            //红字R为负，蓝字B正
            if (resultMap.get(AccountBizConstant.RULE_RESULT_SIGN).equals(AccountBizConstant.SIGN_RED)) {
                gaVoucherInfo.setAmount(info.getAmount().negate());
            } else {
                gaVoucherInfo.setAmount(info.getAmount());
            }
            gaVoucherInfo.setTxnCode(info.getTxnCode());
            //币种
            gaVoucherInfo.setCurrency(AccountBizConstant.CURRENCY);
            gaVoucherInfo.setLoanId(info.getLoanId());
            gaVoucherInfo.setCustomerId(info.getCustomerId());
            gaVoucherInfo.setAccountId(info.getTxnAccountId());
            gaVoucherInfo.setDescription(info.getTxnDesc());
            //传票类型-->更新科目总账
            gaVoucherInfo.setVoucherType(TransBizConstant.TYPE_G);
            //传票来源--> 核心账务组件 F 资金源
            gaVoucherInfo.setSrc(TransBizConstant.SRC_F);
            gaVoucherInfo.setProductId(info.getLoanProductId());
            gaVoucherInfo.setChannel(info.getChannel());
            gaVoucherInfo.setLoanClassify(info.getLoanClassify());
            gaVoucherInfo.setCategory(info.getCategory());
            gaVoucherInfo.setUpdateBy(AccountBizConstant.USER_NAME);
            gaVoucherInfo.setRecordVersionNumber(1);
            gaVoucherInfo.setInvestorId(info.getInvestorId());
            String feeCode=String.valueOf(resultMap.get(AccountBizConstant.RULE_RESULT_FEE_CODE));
            if(StringUtils.isNotBlank(feeCode)){
                gaVoucherInfo.setPriceTxaCode(feeCode);
            }else{
                gaVoucherInfo.setPriceTxaCode("");
            }

            voucherInfoList.add(gaVoucherInfo);
        }
        return voucherInfoList;
    }
}
